const db = wx.cloud.database()
const FORMAT = require("util.js")
const _ = db.command
const $ = db.command.aggregate
module.exports = {

  /**
   * @description: 获取用户openid
   * @type: 云函数
   * @param none
   * @return res.result.openid
   */
  getOpenID: function () {
    return new Promise(function (resolve, reject) {
      wx.cloud.callFunction({
        name: 'login',
        data: {},
      }).then(res => {
        resolve(res.result.openid)
      }).catch(err => {
        console.error('[云函数] [getOpenID] 调用失败', err)
        reject(err)
      })
    })
  },

  /**
   * @description: 按状态查询信件
   * @type: 云函数
   * @param status
   * @return res.result.data
   */
  getXinJianByStatus: function (status) {
    return new Promise(function (resolve, reject) {
      wx.cloud.callFunction({
        name: 'getdata',
        data: {
          action: "getXinJianByStatus",
          status: status
        },
      }).then(res => {
        resolve(res.result.data)
      }).catch(err => {
        console.error('[云函数] [getXinJianByStatus] 调用失败', err)
        reject(err)
      })
    })
  },

  /**
   * @description: 添加文章评论
   * @type: 云函数
   * @param id, pinLun
   * @return res
   */
  updatePinLun: function (id, pinLun) {
    return new Promise(function (resolve, reject) {
      wx.cloud.callFunction({
        name: 'updatedata',
        data: {
          action: "updatePinLun",
          id: id,
          pinLun: pinLun
        },
      }).then(res => {
        resolve(res)
      }).catch(err => {
        console.error('[云函数] [updatePinLun] 调用失败', err)
        reject(err)
      })
    })
  },

  /**
   * @description: 更新信件状态
   * @type: 云函数
   * @param id, status
   * @return res
   */
  updateXinJianStatus: function (id, status) {
    return new Promise(function (resolve, reject) {
      wx.cloud.callFunction({
        name: 'updatedata',
        data: {
          action: "updateXinJianStatus",
          id: id,
          status: status
        },
      }).then(res => {
        resolve(res)
      }).catch(err => {
        console.error('[云函数] [updateXinJianStatus] 调用失败', err)
        reject(err)
      })
    })
  },

  /**
   * @description: 添加笔友
   * @type: 云函数
   * @param openid, biyoudata
   * @return res
   */
  updateBiYouList: function (openid, biyoudata) {
    return new Promise(function (resolve, reject) {
      wx.cloud.callFunction({
        name: 'updatedata',
        data: {
          action: "updateBiYouList",
          openid: openid,
          biyoudata: biyoudata
        },
      }).then(res => {
        resolve(res)
      }).catch(err => {
        console.error('[云函数] [updateBiYouList] 调用失败', err)
        reject(err)
      })
    })
  },

  /**
   * @description: 联表查询用户是否参与了每日话题
   * @type: 云函数
   * @param id
   * @return res.result
   */
  getCommentStatus: function (id) {
    return new Promise(function (resolve, reject) {
      wx.cloud.callFunction({
        name: 'getdata',
        data: {
          action: "getCommentStatus",
          huaTiId: id
        },
      }).then(res => {
        resolve(res.result)
      }).catch(err => {
        reject("获取数据出错了，请重试！")
        console.error('[云函数] [getCommentStatus] 调用失败', err)
      })

    })
  },

  /**
   * @description: 每日话题投票方法
   * @type: 云函数
   * @param result, id
   * @return res.result
   */
  updateHuaTiNumber: function (result, id) {
    return new Promise(function (resolve, reject) {
      wx.cloud.callFunction({
        name: 'updatedata',
        data: {
          action: "updateHuaTiNumber",
          result: result,
          id: id
        },
      }).then(res => {
        resolve(res.result)
      }).catch(err => {
        reject("获取数据出错了，请重试！")
        console.error('[云函数] [updateHuaTiNumber] 调用失败', err)
      })

    })
  },

  /**
   * @description: 添加话题评论
   * @type: 云函数
   * @param id, pinLun
   * @return res
   */
  updateHuaTiPinLun: function (id, pinLun) {
    return new Promise(function (resolve, reject) {
      wx.cloud.callFunction({
        name: 'updatedata',
        data: {
          action: "updateHuaTiPinLun",
          id: id,
          pinLun: pinLun
        },
      }).then(res => {
        resolve(res)
      }).catch(err => {
        console.error('[云函数] [updateHuaTiPinLun] 调用失败', err)
        reject(err)
      })
    })
  },

  /**
   * @description: 更新名字
   * @type: 云函数
   * @param biming 
   * @return res
   */
  updateBiMing: function (biming) {
    return new Promise(function (resolve, reject) {
      wx.cloud.callFunction({
        name: 'updatedata',
        data: {
          action: "updateBiMing",
          biMing: biming
        },
      }).then(res => {
        resolve(res)
      }).catch(err => {
        console.error('[云函数] [updateBiMing] 调用失败', err)
        reject(err)
      })
    })
  },

  /**
   * @description: 发信时检测邮箱容量
   * @type: 云函数
   * @param collection, id 
   * @return res 
   */
  deleteCollectionItem: function (collection, id) {
    return new Promise(function (resolve, reject) {
      wx.cloud.callFunction({
        name: 'updatedata',
        data: {
          action: "deleteCollectionItem",
          collection: collection,
          id: id
        },
      }).then(res => {
        resolve(res)
      }).catch(err => {
        console.error('[云函数] [deleteCollectionItem] 调用失败', err)
        reject(err)
      })
    })
  },

  /**
   * @description: 检测文字内容安全
   * @type: 云函数
   * @param content
   * @return res 
   */
  checkWenZhiNeiRong: function (content) {
    return new Promise(function (resolve, reject) {
      wx.cloud.callFunction({
        name: "checkContent",
        data: {
          content: content,
        }
      }).then((res) => {
        resolve(res)
      }).catch(err => {
        console.error('[云函数] [checkWenZhiNeiRong] 调用失败', err)
        reject(err)
      })
    })
  },

  /**
   * @description: 检测图片内容安全
   * @type: 云函数
   * @param content
   * @return res 
   */
  checkImageContent: function (content) {
    return new Promise(function (resolve, reject) {
      wx.getFileSystemManager().readFile({
        filePath: content,
        encoding: "base64",
        success: (res) => {
          wx.cloud.callFunction({
            name: "checkContent",
            data: {
              base64: res.data,
            }
          }).then((res) => {
            resolve(res)
          }).catch(err => {
            console.error('[云函数] [checkImageContent] 调用失败', err)
            reject(err)
          })
        }
      })
    })
  },



  /**
   * @description: 删除文章
   * @type: 普通函数
   * @param id 
   * @return res
   */
  removeWenZhang: function (id) {
    return new Promise(function (resolve, reject) {
      db.collection("wenzhangbiao").where({
          _id: id
        }).remove().then(res => {
          resolve(res)
        })
        .catch(err => {
          reject("获取数据出错了，请重试！")
          console.error(err)
        })
    })
  },

  /**
   * @description: 随机获取集合中没有超过时限的5条数据
   * @type: 聚合函数
   * @param collection, endtime, count
   * @return res.data
   */
  getXianShiArticle: function (collection, endtime, count) {
    return new Promise(function (resolve, reject) {
      db.collection(collection)
        .aggregate()
        .match({
          jieShuShiJian: _.gte(endtime)
        })
        .sample({
          size: count
        })
        .end()
        .then(res => {
          resolve(res.list)
        })
        .catch(err => {
          reject("获取数据出错了，请重试！")
          console.error(err)
        })
    })
  },

  /**
   * @description: 随机获取集合中N条数据
   * @type: 聚合函数
   * @param collection, count
   * @return res.list
   */
  getRandomArticle: function (collection, count) {
    return new Promise(function (resolve, reject) {
      db.collection(collection)
        .aggregate()
        .sample({
          size: count
        })
        .end()
        .then(res => {
          resolve(res.list)
        })
        .catch(err => {
          reject("获取数据出错了，请重试！")
          console.error(err)
        })
    })
  },

  /**
   * @description: 获取集合中分类数据
   * @type: 聚合函数
   * @param collection, type, count
   * @return res.list
   */
  getTypeArticle: function (collection, type, count) {
    return new Promise(function (resolve, reject) {
      db.collection(collection)
        .aggregate()
        .match({
          leiXing: type
        })
        .sample({
          size: count
        })
        .end()
        .then(res => {
          resolve(res.list)
        })
        .catch(err => {
          reject("获取数据出错了，请重试！")
          console.error(err)
        })
    })
  },

  /**
   * @description: 根据openid获取用户信息
   * @type: 普通函数
   * @param openid
   * @return res.data
   */
  getUserDataByOpenId: function (openid) {
    return new Promise(function (resolve, reject) {
      db.collection("userInfo").where({
          _openid: openid
        }).get().then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject("获取数据出错了，请重试！")
          console.error(err)
        })
    })
  },

  /**
   * @description: 初始化新用户数据
   * @type: 普通函数
   * @param data
   * @return res._id
   */
  initUserInfo: function (data) {
    let touXiangUrl = ""
    if (data.gender == 1) {
      touXiangUrl = "https://7377-sweetsandbitters-9fd1y-1303162053.tcb.qcloud.la/systemimages/nan.png?sign=74b0bc01fa36364c98e74535ba06c47a&t=1599986815"
    } else {
      touXiangUrl = "https://7377-sweetsandbitters-9fd1y-1303162053.tcb.qcloud.la/systemimages/nv.png?sign=55191aeb998c6dfa00af2f6e029520cb&t=1599986829"
    }

    return new Promise(function (resolve, reject) {
      let userInfo = {
        isManager: false,
        biMing: "苦海匿舟",
        shengFenDengJi: 0,
        xingBie: data.gender,
        touXiang: touXiangUrl,
        faJianRenXinFengUrl: "https://7377-sweetsandbitters-9fd1y-1303162053.tcb.qcloud.la/xinfenimages/init.jpg?sign=3e9060351a452b86661f995287d452ec&t=1599990230",
        jiFeng: 0,
        chengZhangZhi: 0,
        wenZhangZongShu: 0,
        shiGuangPingShuLiang: 5,
        biYouShuLiang: 3,
        biYouLieBiao: [],
        zhuCheShiJian: FORMAT.formatDay(Math.floor(new Date().getTime() / 1000))
      }
      db.collection("userInfo").add({
        data: userInfo
      }).then(res => {
        resolve(res._id)
      }).catch(err => {
        reject("获取数据出错了，请重试！")
        console.error(err)
      })
    })
  },

  /**
   * @description: 给某集合添加数据
   * @type: 普通函数
   * @param collection, data
   * @return res._id
   */
  tianJiaShuJu: function (collection, data) {
    return new Promise(function (resolve, reject) {
      db.collection(collection).add({
        data: data
      }).then(res => {
        resolve(res._id)
      }).catch(err => {
        reject("获取数据出错了，请重试！")
        console.error(err)
      })
    })

  },

  /**
   * @description: 根据ID获取集合中一条数据
   * @type: 普通函数
   * @param collection, id
   * @return res.data
   */
  getDataById: function (collection, id) {
    return new Promise(function (resolve, reject) {
      db.collection(collection).where({
          _id: id
        }).get().then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject("获取数据出错了，请重试！")
          console.error(err)
        })
    })
  },

  /**
   * @description: 获取当日话题
   * @type: 普通函数
   * @param date
   * @return res.data
   */
  getHuatiByDay: function (date) {
    return new Promise(function (resolve, reject) {
      db.collection("huati").where({
          date: date
        }).get().then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject("获取数据出错了，请重试！")
          console.error(err)
        })
    })
  },

  /**
   * @description: 根据openid与时间获取时光瓶数据
   * @type: 普通函数
   * @param openid, date 
   * @return res.data
   */
  getShiGuangPingDataByOpenId: function (openid, date) {
    return new Promise(function (resolve, reject) {
      db.collection("shiguangping").where({
          _openid: openid,
          status: 0,
          jieShuShiJian: _.lte(date)
        }).get().then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject("获取数据出错了，请重试！")
          console.error(err)
        })
    })
  },

  /**
   * @description: 根据openid获取文章数据
   * @type: 普通函数
   * @param openid 
   * @return res.data
   */
  getWenZhangDataByOpenId: function (openid) {
    return new Promise(function (resolve, reject) {
      db.collection("wenzhangbiao").where({
          _openid: openid
        }).get().then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject("获取数据出错了，请重试！")
          console.error(err)
        })
    })
  },

  /**
   * @description: 获取公告数据
   * @type: 普通函数
   * @param none 
   * @return res.data
   */
  getNotice: function () {
    return new Promise(function (resolve, reject) {
      db.collection("systemnotices").get().then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject("获取数据出错了，请重试！")
          console.error(err)
        })
    })
  },

  /**
   * @description: 登录时获取各服务状态
   * @type: 普通函数
   * @param none 
   * @return res.total
   */
  getDataStatus: function () {
    return new Promise(function (resolve, reject) {
      db.collection('order').where({
        _openid: OPENID,
        orderStatus: 1
      }).count().then(res => {
        resolve(res.total)
      }).catch(err => {
        reject("获取数据出错了，请重试！")
        console.error(err)
      })

    })
  },

  /**
   * @description: 发信时检测邮箱容量
   * @type: 普通函数
   * @param openid 
   * @return res
   */
  checkCountNumber: function (collection, openid) {
    return new Promise(function (resolve, reject) {
      db.collection(collection).where({
          _openid: openid
        }).count().then(res => {
          resolve(res)
        })
        .catch(err => {
          reject("获取数据出错了，请重试！")
          console.error(err)
        })
    })
  },

  /**
   * @description: 删除文章时一并删除文章中的图片释放容量
   * @type: 普通函数
   * @param imagesList
   * @return {res} 
   */
  deleteImagesList: function (imagesList) {
    return new Promise(function (resolve, reject) {
      wx.cloud.deleteFile({
        fileList: imagesList,
        success: res => {
          resolve(res.fileList)
        },
        fail: err => {
          console.error('[函数] [deleteImagesList] 调用失败', err)
          reject(err)
        }
      })
    })
  }
}